#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/6/20 16:46
# @Author  : Chenmm
# @File    : message_method.py
# @Software: PyCharm


import traceback
from datetime import datetime
from sqlalchemy.orm import Session
from sqlalchemy import or_

from methods.user_method import get_user_by_username, get_user_by_uid
from models.message_schema import MessageContent, MessagePid, MessageOne, RebackMessage
from models.models import Message, User
from models.user_schema import UsernameRole
from common.log import logger
from common.json_tools import response


def add_message_method(message_content: MessageContent, user: UsernameRole, db: Session):
    """添加留言"""
    logger.info(f"用户:{user.username}来留言了")
    accept_user = get_user_by_uid(db, message_content.accept_uid)
    if not accept_user:
        return response(code=100503, message="接收留言的用户不存在")
    _user = get_user_by_username(db, user.username)
    if accept_user.id == _user.id:
        return response(code=100501, message="自己不能给自己留言")
    current_time = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
    try:
        message = Message(
            send_user=_user.id,
            accept_user=accept_user.id,
            context=message_content.content,
            send_time=current_time,
            add_time=current_time
        )
        db.add(message)
        db.commit()
        db.refresh(message)
    except:
        logger.warning(f"method add_message_method error：{traceback.format_exc()}")
        return response(code=100502, message="留言失败")
    logger.info(f"用户：{user.username}留言成功")
    return response(data="留言成功")


def get_msg_by_id(db, msg_id):
    return db.query(Message).filter(Message.id == msg_id, Message.status == 0).first()


def get_pid_message(db, msg_id):
    # 获取某条消息被回复的所有消息
    return db.query(Message).filter(Message.pid == msg_id, Message.status == 0).all()


def view_msg_method(msg_id: int, user: UsernameRole, db: Session):
    """查看留言(回复的消息和留言在一个表里，结构一样)"""
    msg = get_msg_by_id(db, msg_id)
    if not msg:
        return response(code=100601, message="留言不存在")
    db_user = get_user_by_username(db, user.username)
    if msg.accept_user != db_user.id:
        return response(code=100602, message="权限不足")
    msg.read = True
    db.commit()
    db.refresh(msg)
    all_pid_messages = get_pid_message(db, msg_id)  # 查询所有回复的消息
    message_one = MessageOne(
        id=msg.id,
        send_user=get_user_by_uid(db, msg.send_user).username,
        accept_user=get_user_by_uid(db, msg.accept_user).username,
        read=msg.read,
        send_time=msg.send_time,
        add_time=str(msg.add_time),
        context=msg.context
    )
    # ① 留言没有被回复消息
    if not all_pid_messages:
        return response(data=message_one.model_dump())
    # ② 留言有被回复的消息，那么需要将回复的消息带回
    to_client = []
    for _ in all_pid_messages:
        msg_pid = MessagePid(
            id=_.id,
            send_user=get_user_by_uid(db, _.send_user).username,
            accept_user=get_user_by_uid(db, _.accept_user).username,
            read=_.read,
            send_time=_.send_time,
            add_time=str(_.add_time),
            context=_.context,
            pid=_.pid
        )
        to_client.append(msg_pid)
    message_one.pid = to_client
    return response(data=message_one.model_dump())


def get_msg_list(db: Session, uid: int):
    # 查询留言+回复
    return db.query(Message).filter(or_(Message.send_user == uid, Message.accept_user == uid)).filter(Message.status == 0).all()


def list_msg_method(user: UsernameRole, db: Session):
    """获取留言列表"""
    db_user = get_user_by_username(db, user.username)
    msg_list = get_msg_list(db, db_user.id)  # 获取与当前用户相关留言/回复
    to_client = []
    main_msg_id_list = []
    if msg_list:
        for _ in msg_list:
            # ① 如果是留言
            if _.pid is None:
                message_one = MessageOne(
                    id=_.id,
                    send_user=get_user_by_uid(db, _.send_user).username,
                    accept_user=get_user_by_uid(db, _.accept_user).username,
                    read=_.read,
                    send_time=_.send_time,
                    add_time=str(_.add_time),
                    context=_.context
                )
                main_msg_id_list.append(_.id)  # 保存非回复信息的id，即留言信息的id
                # 查询该留言信息的所有回复信息,并将回复信息一并返回
                all_pid_messages = get_pid_message(db, _.id)
                if all_pid_messages:
                    to_client_pid_msgs = []
                    for _ in all_pid_messages:
                        message_pid = MessagePid(
                            id=_.id,
                            send_user=get_user_by_uid(db, _.send_user).username,
                            accept_user=get_user_by_uid(db, _.accept_user).username,
                            read=_.read,
                            send_time=_.send_time,
                            add_time=str(_.add_time),
                            context=_.context,
                            pid=_.pid
                        )
                        to_client_pid_msgs.append(message_pid.model_dump())
                    message_one.pid = to_client_pid_msgs
                to_client.append(message_one.model_dump())
            # ② 如果是回复,查询该回复信息是否有主留言信息，如果有同上
            else:
                if _.pid not in main_msg_id_list:
                    _msg = get_msg_by_id(db, _.pid)
                    if _msg:
                        _all_pid_messages = get_pid_message(db, _msg.id)
                        _message_one = MessageOne(
                            id=_msg.id,
                            send_user=get_user_by_uid(db, _msg.send_user).username,
                            accept_user=get_user_by_uid(db, _msg.accept_user).username,
                            read=_msg.read,
                            send_time=_msg.send_time,
                            add_time=str(_msg.add_time),
                            context=_msg.context
                        )
                        if _all_pid_messages:
                            _pid_list = []
                            for each in _all_pid_messages:
                                _message_pid = MessagePid(
                                    id=each.id,
                                    send_user=get_user_by_uid(db, each.send_user).username,
                                    accept_user=get_user_by_uid(db, each.accept_user).username,
                                    read=each.read,
                                    send_time=each.send_time,
                                    add_time=str(each.add_time),
                                    context=each.context,
                                    pid=each.pid
                                )
                                _pid_list.append(_message_pid.model_dump())
                            _message_one.pid = _pid_list
                        to_client.append(_message_one.model_dump())
    return response(data=to_client)



def insert_reback_msg(reback: RebackMessage, send_user: User, db: Session):
    try:
        current_time = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
        message = Message(
            send_user=send_user.id,
            accept_user=reback.accept_uid,
            send_time=current_time,
            pid=reback.rebackid,
            context=reback.content
        )
        db.add(message)
        db.commit()
        db.refresh(message)
    except:
        logger.warning(f"method insert_reback_msg method error: {traceback.format_exc()}")
        return response(code=100801, message="回复失败")


def reback_msg(reback_message: RebackMessage, send_user: UsernameRole, db: Session):
    """回复留言"""
    db_user = get_user_by_username(db, send_user.username)
    db_msg = get_msg_by_id(db, reback_message.rebackid)
    if not db_msg:
        return response(code=100804, message="回复留言不存在")
    insert_reback_msg(reback_message, db_user, db)
    return response()


def delete_msg(msg_id: int, user: UsernameRole, db: Session):
    """删除留言"""
    db_msg = get_msg_by_id(db, msg_id)
    if not db_msg:
        return response(code=100901, message="删除留言不存在")
    db_user = get_user_by_username(db, user.username)
    if db_user.id != db_msg.send_user:
        return response(code=100902, message="权限不足")
    try:
        db_msg.status = 1
        db.commit()
        db.refresh(db_msg)
    except:
        logger.warning(f"method delete_msg error: {traceback.format_exc()}")
        response(code=100903, message="删除失败")
    return response()